/**
 * easyui基本扩展
 */
(function($){
	/**
	 * 按条件查询
	 * @param condition 查询条件Condition,And,Or
	 */
	$.fn.gridFilter = function(condition){
//		if(typeof condition == "Condition" || typeof condition == "And" || typeof condition == "Or"){
//			alert('yes')
//		}else{
//			//condition = null;
//		}
		$(this).datagrid("load",{condition : condition});
	}
})(jQuery);

function Condition(columnName, operType, value1, value2) {
	this.leftItem = columnName;
	this.operType = operType;
	this.value1 = value1;
	this.value2 = value2;
	this.leftCondition = null;
	this.rightCondition = null;
	this.conditionType = "1";
}

function And(leftCondition, rightCondition) {
	this.leftItem = null;
	this.operType = null;
	this.value1 = null;
	this.value2 = null;
	this.leftCondition = leftCondition;
	this.rightCondition = rightCondition;
	this.conditionType = "2";
}

function Or(leftCondition,rightCondition){
	this.leftItem = null;
	this.operType = null;
	this.value1 = null;
	this.value2 = null;
	this.leftCondition = leftCondition;
	this.rightCondition = rightCondition;
	this.conditionType = "3";
}


/********************************************************
 * 公共函数部分参考来自 孙宇 syspro源码
 * 
 * ******************************************************
 */

var sy = $.extend({}, sy);/* 全局对象 */
/**
 *  判断浏览器是否是IE并且版本小于8 
 */
sy.isLessThanIe8 = function() {
	return ($.browser.msie && $.browser.version < 8);
};

/**
 * datagrid是否格式化
 */
sy.dgYNFormatter = function(value,row,index){
	if(value == 0){
		return "否";
	}
	if(value == 1){
		return "是"
	}
	return value;
}

/**
 * 将form表单数据封闭成json对象
 */
sy.formToJSON = function(formId){
	var data = $("#"+formId).serializeArray();
	var str = "{";
	for(var i = 0; i < data.length;i++){
		str+="\"" + data[i].name + "\":\"" + data[i].value + "\"";
		if(i != data.length-1){
			str+=",";
		}
	}
	str+="}";
	var jsonForm = eval("(" + str + ")");
	return jsonForm;
}

/**
 * 遍历查询表单形成查询条件
 */
sy.listFormCondition = function(formId){
	var conds = new Array();
	$("#" + formId + " :input[name$='.oper']" ).each(function(){
		var name = $(this).attr("name");
		var columnName = name.split(",")[0];
		var operType = $(this).val();
		var val1 = "";
		var val2 = "";
		try {
			val1 = $(columnName+".value1]")[0].value;
			val2 = $(columnName+".value2]")[0].value;
		} catch(e) {
			
		}
		var condition = new Condition(columnName,operType,val1,val2);
		conds.push(condition);
	});
	alert(conds.length);
	if(conds.length == 0 ){
		return null;
	}else if(conds.length == 1){
		return conds[0];
	}else{
		var and;
		for(var i = 1; i < conds.length; i++){
			if(i = 1){
				and = new And(conds[0] + conds[i]);
			}else{
				and = new And(and,conds[i]);
			}
		}
		return and;
	}
} 

/**********************************************
 * easyui的扩展修改
 * ---------------------------------------------
 */
/***************************************************/
/*=======================Tree======================*/
/***************************************************/
/**
 * simpleData加载树数据简单数据结构（扁平pid结构数据集，也就是id，pid形式）
 */
$.fn.tree.defaults.loadFilter = function (data, parent) {
    var opt = $(this).data().tree.options;
    var idFiled,
    textFiled,
    parentField;
    if (opt.parentField) {
        idFiled = opt.idFiled || 'id';
        textFiled = opt.textFiled || 'text';
        parentField = opt.parentField;
        var i,
        l,
        treeData = [],
        tmpMap = [];
        for (i = 0, l = data.length; i < l; i++) {
            tmpMap[data[i][idFiled]] = data[i];
        }
         
        for (i = 0, l = data.length; i < l; i++) {
            if (tmpMap[data[i][parentField]] && data[i][idFiled] != data[i][parentField]) {
                if (!tmpMap[data[i][parentField]]['children'])
                    tmpMap[data[i][parentField]]['children'] = [];
                data[i]['text'] = data[i][textFiled];
                tmpMap[data[i][parentField]]['children'].push(data[i]);
            } else {
                data[i]['text'] = data[i][textFiled];
                treeData.push(data[i]);
            }
        }
        return treeData;
    }
    return data;
};

/***************************************************/
/*=======================Form======================*/
/***************************************************/
/**
 * 使easyui表单只读状态的方法
 * options - boolean类型，或是对象{flag : boolean, func:function}
 */
$.extend($.fn.form.methods, {
	readMode: function(jq,options){
				return jq.each(function(){
					if(typeof options =="boolean"){
						var o = {};
						o.flag = options;
						options = o;
					}else if(typeof options == "object"){
						options = $.extend({flag : false},options);
					}else{
						return;
					}
					var id=$(this).prop("id");
					if(id == null){
						return;
					}
					id="#"+id + " ";
					if (options.flag == true) {
						$(id+"input").attr("disabled","disabled");
				        $(id+"textarea").attr("disabled","disabled");
				        $(id+".easyui-validatebox").validatebox("disableValidation");
				        $(id+".easyui-numberbox").numberbox("disable");
				        $(id+".easyui-datebox").datebox("disable");
				        $(id+".easyui-combobox").combobox("disable");
				        $(id+".easyui-combotree").combotree("disable");
				        $(id+".easyui-combogrid").combogrid("disable");
				    } else {
				    	$(id+"input").removeAttr("disabled");
				        $(id+"textarea").removeAttr("disabled");
				        $(id+".easyui-validatebox").validatebox("enableValidation");
				        $(id+".easyui-numberbox").numberbox("enable");
				        $(id+".easyui-datebox").datebox("enable");
				        $(id+".easyui-combobox").combobox("enable");
				        $(id+".easyui-combotree").combotree("enable");
				        $(id+".easyui-combogrid").combogrid("enable");
				    }
					
					if(options.func && typeof options.func == ("function")){
						options.func();
					}
				});
			}
});

/***************************************************/
/*==================linkbutton======================*/
/***************************************************/
/**
 * 给linkbutton添加绑定click的方法,修复enable和diable方法的bug
 */
$.extend($.fn.linkbutton.methods, {
	click : function(jq, clickFun) {
		return jq.each(function() {
			//$(this).click(clickFun);
			$(this).bind("click",clickFun);
		});
	},
	 /**
	 * 激活选项（覆盖重写）
	 * 
	 * @param {Object}
	 *            jq
	 */
    enable: function(jq){
        return jq.each(function(){
            var state = $.data(this, 'linkbutton');
            if ($(this).hasClass('l-btn-disabled')) {
                var itemData = state._eventsStore;
                // 恢复超链接
                if (itemData.href) {
                    $(this).attr("href", itemData.href);
                }
                // 回复点击事件
                if (itemData.onclicks) {
                    for (var j = 0; j < itemData.onclicks.length; j++) {
                        $(this).bind('click', itemData.onclicks[j]);
                    }
                }
                // 设置target为null，清空存储的事件处理程序
                itemData.target = null;
                itemData.onclicks = [];
                $(this).removeClass('l-btn-disabled');
            }
        });
    },
    /**
	 * 禁用选项（覆盖重写）
	 * 
	 * @param {Object}
	 *            jq
	 */
    disable: function(jq){
        return jq.each(function(){
            var state = $.data(this, 'linkbutton');
             
            if (!state._eventsStore)
                state._eventsStore = {};
            if (!$(this).hasClass('l-btn-disabled')) {
                var eventsStore = {};
                eventsStore.target = this;
                eventsStore.onclicks = [];
                // 处理超链接
                var strHref = $(this).attr("href");
                if (strHref) {
                    eventsStore.href = strHref;
                    $(this).attr("href", "javascript:void(0)");
                }
                // 处理直接耦合绑定到onclick属性上的事件
                var onclickStr = $(this).attr("onclick");
                if (onclickStr && onclickStr != "") {
                    eventsStore.onclicks[eventsStore.onclicks.length] = new Function(onclickStr);
                    $(this).attr("onclick", "");
                }
                // 处理使用jquery绑定的事件
                var eventDatas = $(this).data("events") || $._data(this, 'events');
                if (eventDatas["click"]) {
                    var eventData = eventDatas["click"];
                    for (var i = 0; i < eventData.length; i++) {
                        if (eventData[i].namespace != "menu") {
                            eventsStore.onclicks[eventsStore.onclicks.length] = eventData[i]["handler"];
                            $(this).unbind('click', eventData[i]["handler"]);
                            i--;
                        }
                    }
                }
                state._eventsStore = eventsStore;
                $(this).addClass('l-btn-disabled');
            }
        });
    }
});


/***************************************************/
/*=======================Tabs======================*/
/***************************************************/
/**
 * 根据tab的id将tab从tabs中关闭
 */
$.extend($.fn.tabs.methods,{
	removeByTPId: function(jq,id){
			return jq.each(function(){
				var tabPanels = $(this).tabs("tabs");
				if(tabPanels != null && tabPanels.length!=0){
					for(var i = 0; i < tabPanels.length;i++){
						var tabPanelId = $(tabPanels[i]).panel("options").id;
						if(id == tabPanelId){
							$(this).tabs("close",tabPanels[i].panel("options").title);
						}
					}
				}
			});
		},
	disableWithinSel:function(jq){
			return jq.each(function(){
				var selTab = $(this).tabs("getSelected");
				var tabPanels = $(this).tabs("tabs");
				if(tabPanels != null && tabPanels.length > 1){
					for(var i = 0; i < tabPanels.length;i++){
						tabPanels[i].panel("options").tab.addClass("tabs-disabled");
					}
					selTab.panel("options").tab.removeClass("tabs-disabled");
				}
			});
		},
	enableAll:function(jq){
			return jq.each(function(){
				var tabPanels = $(this).tabs("tabs");
				if(tabPanels != null && tabPanels.length!=0){
					for(var i = 0; i < tabPanels.length;i++){
						$(this).tabs("enableTab",tabPanels[i]);
					}
				}
			});
		}
});
